package com.clps.rulesregulations.util;

import java.io.*;
import java.text.SimpleDateFormat;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.w3c.dom.Document;

/**
 * word 转换成html
 */
public class WordToHtml {

    /**
     * 处理word2007
     *
     * @param inFile
     * @return
     */
    private static int cacheInt = 0;

    public static synchronized String getOnlyId() {
        long curL = System.currentTimeMillis();
        if (curL > curL) {
            cacheInt = 0;
        } else {
            cacheInt += 1;
        }
        return String.valueOf(curL) + String.valueOf(cacheInt);
    }

    public static String Word2007ToHtml(File inFile, String filePath, String fileName, String urlPath) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String randomName = "PIC" + getOnlyId();
        //转换后html中图片src的链接
        final String baseUrl = urlPath + "wordpic/" + randomName + "/";
        //转换后图片存放的位置
        String dir = filePath + "/wordpic/" + randomName + "/";
        File dirF = new File(dir);
        if (!dirF.exists() || !dirF.isDirectory()) {
            dirF.mkdir();
        }
        try {
            XWPFDocument wordDocument = new XWPFDocument(new FileInputStream(inFile));
            XHTMLOptions options = XHTMLOptions.create().URIResolver(new BasicURIResolver(baseUrl));
            File imageFolderFile = new File(dir);
            options.setExtractor(new FileImageExtractor(imageFolderFile));
            XHTMLConverter.getInstance().convert(wordDocument, out, options);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(out.toByteArray());
    }

    public static void main(String[] args) throws Exception {
        WordToHtml wth = new WordToHtml();
        File word2007 = new File("C:/test/中公教育2018年上半年浙江省事业单位统考《职业能力倾向测验》全真模考卷.docx");

//        /** 打印出word2003转换后的html内容*/
//        System.out.println(doWord(word2003));

        /** 打印出word2007转换后的html内容*/
//        System.out.println(doWord2007(word2007));
    }

    /**
     * /**
     * 2003版本word转换成html
     *
     * @throws IOException
     * @throws TransformerException
     * @throws ParserConfigurationException
     */

    public static String Word2003ToHtml(String filePath, String fileName, String urlPath) throws IOException, TransformerException, ParserConfigurationException {

        String htmlName = "test.html";
        final String file = filePath + fileName;
        InputStream input = new FileInputStream(new File(file));
        HWPFDocument wordDocument = new HWPFDocument(input);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        //设置图片存放的位置
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                File imgPath = new File(filePath);
                if (!imgPath.exists()) {//图片目录不存在则创建
                    imgPath.mkdirs();
                }
//                int filename = (int) ((Math.random() * 9 + 1) * 1000000000);
//                String suffix = suggestedName.substring(suggestedName.lastIndexOf(".") + 1);
//                suggestedName = filename + "." + suffix;

                File file = new File(filePath + suggestedName);
                try {
                    OutputStream os = new FileOutputStream(file);
                    os.write(content);
                    os.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return urlPath + suggestedName;
            }
        });

        //解析word文档
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();

//        File htmlFile = new File(filePath + htmlName);
//        OutputStream outStream = new FileOutputStream(htmlFile);

//        //也可以使用字符数组流获取解析的内容
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream outStream = new BufferedOutputStream(baos);

        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outStream);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer serializer = factory.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");

        serializer.transform(domSource, streamResult);
        outStream.close();
        String content = new String(baos.toByteArray());

        return content;
    }
}